package cn.wildfirechat.app.shiro;


import cn.wildfirechat.app.jpa.UserPassword;
import cn.wildfirechat.app.jpa.UserPasswordRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;

@Service
public class AccountPasswordRealm extends AuthorizingRealm {
    @Autowired
    private UserPasswordRepository userPasswordRepository;

    @Autowired
    private CustomCredentialsMatcher customCredentialsMatcher;

    @PostConstruct
    void initRealm() {
        setAuthenticationTokenClass(AccountPasswordToken.class);
        // 使用自定义密码匹配器
        setCredentialsMatcher(customCredentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken instanceof AccountPasswordToken) {
            String userId = (String) authenticationToken.getPrincipal();
            Optional<UserPassword> optional = userPasswordRepository.findById(userId);
            if (optional.isPresent()) {
                UserPassword up = optional.get();
                return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), up.getPassword(), ByteSource.Util.bytes(up.getSalt().getBytes(StandardCharsets.UTF_8)), getName());
            }
        }

        throw new AuthenticationException("没有密码");
    }
}